﻿using Automation.BDaq;
using PerpheralDevice.Units;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;

namespace PerpheralDevice.Advantech;
/// <summary>
/// 研华板卡 输入开关(应用只读开关)
/// </summary>
public class AdvantechSwitchRO :SwitchRO {

    private readonly ushort mfMacAddr;
    private readonly InstantDiCtrl mfInstantDiCtrl;
    public override string UnitID { get; }
    public AdvantechSwitchRO(PerpDev perpDev, InstantDiCtrl instantDiCtrl, int macAddr) {
        this.PerpDev = perpDev;
        this.mfMacAddr = (ushort)macAddr;
        this.UnitID = this.mfMacAddr.ToString();
        this.mfInstantDiCtrl = instantDiCtrl;
    }

    public override SwitchRO View() {
        bool? tempIsOpen = this.GenMockValue();
        if (!this.PerpDev.IsMocking) {
            int port = this.mfMacAddr / 8;
            int bitIndex = this.mfMacAddr % 8;
            this.mfInstantDiCtrl.ReadBit(port, bitIndex, out byte bitVal);
            // 高电平有效
            tempIsOpen = bitVal > 0;
        }

        if (tempIsOpen.HasValue) {
            if (tempIsOpen != this.IsOpen) {
                this.IsOpen = tempIsOpen.Value;
                this.OnStatusChangedRaise();
            }
        }

        return this;
    }

}
